/********
* @version: 0.7.0 - Professional Edition (Coolite Commercial License)
* @author: Coolite Inc. http://www.coolite.com/
* @date: 2008-08-05
* @copyright: Copyright (c) 2006-2008, Coolite Inc. (http://www.coolite.com/). All rights reserved.
* @license: See license.txt and http://www.coolite.com/license/. 
* @website: http://www.coolite.com/
********/

if (!Ext.$) { Ext.$ = Ext.get; }

Ext.namespace("Coolite.Ext");

Coolite.Ext.Version = "0.7.0";

Coolite.Ext.FormViewport = Ext.extend(Ext.Container, {
    initComponent: function() {
        Coolite.Ext.FormViewport.superclass.initComponent.call(this);
        var html = document.getElementsByTagName("html")[0];
        html.className += " x-viewport";
        html.style.height = "100%";
        this.el = Ext.$(document.forms[0]);
        this.el.setHeight = this.el.setWidth = this.el.setSize = Ext.emptyFn;
        this.el.dom.scroll = "no";
        this.allowDomMove = false;
        this.autoWidth = this.autoHeight = true;
        Ext.EventManager.onWindowResize(this.fireResize, this);
        this.renderTo = this.el;
        Ext.getBody().applyStyles({
            overflow: "hidden",
            margin: "0",
            padding: "0",
            border: "0px none",
            height: "100%"
        });
        this.el.applyStyles({ height: "100%", width: "100%" });
    },

    fireResize: function(w, h) {
        this.fireEvent("resize", this, w, h, w, h);
    }
});

Ext.reg("FormViewport", Coolite.Ext.FormViewport);

Ext.layout.FormAnchorLayout = Ext.extend(Ext.layout.AnchorLayout, {
    monitorResize: true,
    getAnchorViewSize : function (ct, target) {
        return target.dom == document.forms[0] ?
                   target.getViewSize() : target.getStyleSize();
    }   
});

Ext.Container.LAYOUTS.formanchor = Ext.layout.FormAnchorLayout;

Ext.layout.FitLayout = Ext.extend(Ext.layout.ContainerLayout, {
    // private
    monitorResize: true,

    // private
    onLayout : function (ct, target) {
        Ext.layout.FitLayout.superclass.onLayout.call(this, ct, target);
        if (!this.container.collapsed) {
            if (target.dom == document.forms[0]) {
                this.setItemSize(this.activeItem || ct.items.itemAt(0), Ext.getBody().getViewSize());
            } else {
                this.setItemSize(this.activeItem || ct.items.itemAt(0), target.getStyleSize());
            }             
        }
    },

    // private
    setItemSize : function (item, size) {
        if (item && size.height > 0) { // display none?
            item.setSize(size);
        }
    }
});

Ext.Container.LAYOUTS.fit = Ext.layout.FitLayout;

Ext.layout.ColumnLayout = Ext.extend(Ext.layout.ContainerLayout, {
    monitorResize: true,
    extraCls: "x-column",
    scrollOffset: 0,
    margin: 0,
    split: false,
    fitHeight: false,

    // private
    isValidParent: function(c, target) {
        return c.getEl().dom.parentNode == this.innerCt.dom;
    },

    renderAll: function(ct, target) {
        if (this.split && !this.splitBars) {
            this.splitBars = [];
            this.margin = 5;
        }

        Ext.layout.ColumnLayout.superclass.renderAll.apply(this, arguments);
    },

    // private
    onLayout: function(ct, target) {
        var cs = ct.items.items, len = cs.length, c, cel, i;

        if (!this.innerCt) {
            target.addClass("x-column-layout-ct");
            this.innerCt = target.createChild({ cls: "x-column-inner", style: { position: "relative"} });
            this.innerCt.createChild({ cls: "x-clear" });
        }
        this.renderAll(ct, this.innerCt);

        var size = Ext.isIE && target.dom != Ext.getBody().dom ? target.getStyleSize() : target.getViewSize();

        if (size.width < 1 && size.height < 1) { // display none?
            return;
        }

        var w = size.width - target.getPadding("lr") - this.scrollOffset,
            h = size.height - target.getPadding("tb");
        this.availableWidth = w;
        var pw = this.availableWidth;

        if (this.split) {
            this.minWidth = Math.min(pw / len, 100);
            this.maxWidth = pw - ((this.minWidth + 5) * (len ? (len - 1) : 1));
        }

        if (this.fitHeight) {
            this.innerCt.setSize(w, h);
        }
        else {
            this.innerCt.setWidth(w);
        }

        var lastProportionedColumn;
        for (i = 0; i < len; i++) {
            c = cs[i];
            cel = c.getEl();

            if (this.margin && (i < (len - 1))) {
                cel.setStyle("margin-right", this.margin + "px");
            }
            if (c.columnWidth) {
                lastProportionedColumn = i;
            } else {
                pw -= (c.getSize().width + cel.getMargins("lr"));
            }
        }

        var remaining = (pw = pw < 0 ? 0 : pw);

        var splitterPos = 0, cw;
        for (i = 0; i < len; i++) {
            c = cs[i];
            cel = c.getEl();
            if (c.columnWidth) {
                cw = (i == lastProportionedColumn) ? remaining : Math.floor(c.columnWidth * pw);
                c.setSize(cw - cel.getMargins("lr"), this.fitHeight ? h : null);
                remaining -= cw;
            } else if (this.fitHeight) {
                c.setHeight(h);
            }

            if (this.split) {
                cw = cel.getWidth();

                if (i < (len - 1)) {
                    splitterPos += cw;
                    if (this.splitBars[i]) {
                        this.splitBars[i].el.setHeight(h);
                    } else {
                        this.splitBars[i] = new Ext.SplitBar(this.innerCt.createChild({
                            cls: "x-layout-split x-layout-split-west",
                            style: {
                                top: "0px",
                                left: splitterPos + "px",
                                height: h + "px"
                            }
                        }), cel);
                        this.splitBars[i].index = i;
                        this.splitBars[i].leftComponent = c;
                        this.splitBars[i].addListener("resize", this.onColumnResize, this);
                        this.splitBars[i].minSize = this.minWidth;
                    }

                    splitterPos += this.splitBars[i].el.getWidth();
                }

                delete c.columnWidth;
            }
        }

        if (this.split) {
            this.setMaxWidths();
        }
    },

    //  On column resize, explicitly size the Components to the left and right of the SplitBar
    onColumnResize: function(sb, newWidth) {
        if (sb.dragSpecs.startSize) {
            sb.leftComponent.setWidth(newWidth);
            var items = this.container.items.items;
            var expansion = newWidth - sb.dragSpecs.startSize;
            for (var i = sb.index + 1, len = items.length; expansion && i < len; i++) {
                var c = items[i];
                var w = c.el.getWidth();
                newWidth = w - expansion;
                if (newWidth < this.minWidth) {
                    c.setWidth(this.minWidth);
                } else if (newWidth > this.maxWidth) {
                    expansion -= (newWidth - this.maxWidth);
                    c.setWidth(this.maxWidth);
                } else {
                    c.setWidth(c.el.getWidth() - expansion);
                    break;
                }
            }
            this.setMaxWidths();
        }
    },

    setMaxWidths: function() {
        var items = this.container.items.items;

        var spare = items[items.length - 1].el.dom.offsetWidth - 100;

        for (var i = items.length - 2; i > -1; i--) {
            var sb = this.splitBars[i], sbel = sb.el, c = items[i], cel = c.el;
            var itemWidth = cel.dom.offsetWidth;
            sbel.setStyle("left", (cel.getX() - Ext.fly(cel.dom.parentNode).getX() + itemWidth) + "px");
            sb.maxSize = itemWidth + spare;
            spare = itemWidth - 100;
        }
    },

    onResize: function() {
        if (this.split) {
            var items = this.container.items.items;
            if (items[0].rendered) {
                var tw = 0, c;
                for (var i = 0; i < items.length; i++) {
                    c = items[i];
                    tw += c.el.getWidth() + c.el.getMargins("lr");
                }
                for (var j = 0; j < items.length; j++) {
                    c = items[j];
                    c.columnWidth = (c.el.getWidth() + c.el.getMargins("lr")) / tw;
                }
            }
        }
        Ext.layout.ColumnLayout.superclass.onResize.apply(this, arguments);
    }
});

Ext.Container.LAYOUTS.column = Ext.layout.ColumnLayout;

Ext.apply(Ext.lib.Ajax, {
    serializeForm: function(form) {
        if (typeof form == "string") {
            form = (document.getElementById(form) || document.forms[form]);
        }

        var el, name, val, disabled, data = "", hasSubmit = false;
        hasSubmit = form.ignoreAllSubmitFields || false;
        for (var i = 0; i < form.elements.length; i++) {
            el = form.elements[i];
            disabled = form.elements[i].disabled;
            name = form.elements[i].name;
            val = form.elements[i].value;

            if (!disabled && name) {
                switch (el.type) {
                    case "select-one":
                    case "select-multiple":
                        for (var j = 0; j < el.options.length; j++) {
                            if (el.options[j].selected) {
                                if (Ext.isIE) {
                                    data += encodeURIComponent(name) + "=" + encodeURIComponent(el.options[j].attributes.value.specified ? el.options[j].value : el.options[j].text) + "&";
                                } else {
                                    data += encodeURIComponent(name) + "=" + encodeURIComponent(el.options[j].hasAttribute("value") ? el.options[j].value : el.options[j].text) + "&";
                                }
                            }
                        }
                        break;
                    case "radio":
                    case "checkbox":
                        if (el.checked) {
                            data += encodeURIComponent(name) + "=" + encodeURIComponent(val) + "&";
                        }
                        break;
                    case "file":
                    case undefined:
                    case "reset":
                    case "button":
                        break;
                    case "submit":
                        if (hasSubmit === false) {
                            data += encodeURIComponent(name) + "=" + encodeURIComponent(val) + "&";
                            hasSubmit = true;
                        }
                        break;
                    default:
                        data += encodeURIComponent(name) + "=" + encodeURIComponent(val) + "&";
                        break;
                }
            }
        }
        data = data.substr(0, data.length - 1);
        return data;
    }
});


Coolite.Ext.on = function(target, eventName, handler, scope, mode, cfg) {
    var el = target;
    if (typeof target == "string") {
        el = Ext.$(target);
    }

    if (!Ext.isEmpty(el)) {
        if (mode && mode == "client") {
            el.on(eventName, handler.fn, scope, handler);
        } else {
            el.on(eventName, handler, scope, cfg);
        }
    }
};


Ext.form.Hidden.override({
    setValue: function(v) {
        this.value = v;
        var temp = this.el.dom.value;
        if (this.rendered) {
            this.el.dom.value = (v === null || v === undefined ? "" : v);
            this.validate();
        }
        if (this.el.dom.value != temp) {
            this.fireEvent("change");
        }
    }
});

Ext.form.Label.override({
    onRender: function(ct, position) {
        if (!this.el) {
            this.el = document.createElement(this.forId ? "label" : "span");
            this.el.id = this.getId();
            this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || "");
            if (this.forId) {
                this.el.setAttribute("htmlFor", this.forId);
            }
        }
        Ext.form.Label.superclass.onRender.call(this, ct, position);
    } 
});

Ext.form.ComboBox.override({
    initSelect: false,

    setValueAndFireSelect: function(v) {
        this.setValue(v);

        var r = this.findRecord(this.valueField, v);

        if (!Ext.isEmpty(r)) {
            var index = this.store.indexOf(r);
            this.initSelect = true;
            this.fireEvent("select", this, r, index);
            this.initSelect = false;
        }
    }, 

    getSelectedIndex: function() {
        var r = this.findRecord(this.valueField, this.getValue());
        return (!Ext.isEmpty(r)) ? this.store.indexOf(r) : -1;
    }
});

Ext.ns("Ext.ux.layout");

Ext.ux.layout.CenterLayout = Ext.extend(Ext.layout.FitLayout, {
    // private
    setItemSize: function(item, size) {
        this.container.addClass("ux-layout-center");
        item.addClass("ux-layout-center-item");
        if (item && size.height > 0) {
            if (item.width) {
                size.width = item.width;
            }
            item.setSize(size);
        }
    }
});
Ext.Container.LAYOUTS["ux.center"] = Ext.ux.layout.CenterLayout;

Ext.ux.layout.RowLayout = Ext.extend(Ext.layout.ContainerLayout, {
    // private
    monitorResize: true,

    // private
    isValidParent: function(c, target) {
        return c.getEl().dom.parentNode == this.innerCt.dom;
    },

    // private
    onLayout: function(ct, target) {
        var rs = ct.items.items, len = rs.length, r, i;

        if (!this.innerCt) {
            target.addClass("ux-row-layout-ct");
            this.innerCt = target.createChild({ cls: "x-row-inner" });
        }
        this.renderAll(ct, this.innerCt);

        var size = target.getViewSize();

        if (size.width < 1 && size.height < 1) { // display none?
            return;
        }

        var h = size.height - target.getPadding("tb"),
        ph = h;

        this.innerCt.setSize({ height: h });

        // some rows can be percentages while others are fixed
        // so we need to make 2 passes

        for (i = 0; i < len; i++) {
            r = rs[i];
            if (!r.rowHeight) {
                ph -= (r.getSize().height + r.getEl().getMargins("tb"));
            }
        }

        ph = ph < 0 ? 0 : ph;

        for (i = 0; i < len; i++) {
            r = rs[i];
            if (r.rowHeight) {
                r.setSize({ height: Math.floor(r.rowHeight * ph) - r.getEl().getMargins("tb") });
            }
        }
    }

    /**
    * @property activeItem
    * @hide
    */
});
Ext.Container.LAYOUTS["ux.row"] = Ext.ux.layout.RowLayout;

Ext.Toolbar.HtmlElement = function(config) {
    Ext.Toolbar.HtmlElement.superclass.constructor.call(this, config.target);
};
Ext.extend(Ext.Toolbar.HtmlElement, Ext.Toolbar.Item, {});
Ext.reg("tbhtml", Ext.Toolbar.HtmlElement);

Ext.override(Ext.Component, {
    addPlugins: function(plugins) {
        if (this.plugins === undefined) {
            this.plugins = [];
        } else if (!Ext.isArray(this.plugins)) {
            this.plugins = [this.plugins];
        }
        if (Ext.isArray(plugins)) {
            for (var i = 0; i < plugins.length; i++) {
                this.plugins.push(this.initPlugin(plugins[i]));
            }
        } else {
            this.plugins.push(this.initPlugin(plugins));
        }
    }
});

Coolite.Ext.DateItem = function(config) {
    Coolite.Ext.DateItem.superclass.constructor.call(this, new Ext.DatePicker(config.picker || {}), config);
    this.picker = this.component;
    this.addEvents("select");

    this.picker.on("render", function(picker) {
        picker.getEl().swallowEvent("click");
        picker.container.addClass("x-menu-date-item");
    });

    this.picker.on("select", this.onSelect, this);
};

Ext.extend(Coolite.Ext.DateItem, Ext.menu.Adapter, {
    // private
    onSelect: function(picker, date) {
        this.fireEvent("select", this, date, picker);
        Coolite.Ext.DateItem.superclass.handleClick.call(this);
    }
});

Coolite.Ext.DateMenu = function(config) {
    Coolite.Ext.DateMenu.superclass.constructor.call(this, config);
    this.plain = true;
    var di = new Coolite.Ext.DateItem(config);
    this.add(di);
    this.picker = di.picker;
    this.relayEvents(di, ["select"]);

    this.on("beforeshow", function() {
        if (this.picker) {
            this.picker.hideMonthPicker(true);
        }
    }, this);
};
Ext.extend(Coolite.Ext.DateMenu, Ext.menu.Menu, {
    cls: "x-date-menu",

    // private
    beforeDestroy: function() {
        this.picker.destroy();
    }
});

Ext.override(Ext.ColorPalette, {
    silentSelect: function(color) {
        color = color.replace("#", "");
        if (color != this.value || this.allowReselect) {
            var el = this.el;
            if (this.value) {
                el.child("a.color-" + this.value).removeClass("x-color-palette-sel");
            }
            el.child("a.color-" + color).addClass("x-color-palette-sel");
            this.value = color;
        }
    }
});

Coolite.Ext.ColorItem = function(config) {
    Coolite.Ext.ColorItem.superclass.constructor.call(this, new Ext.ColorPalette(config.palette), config);
    this.palette = this.component;
    this.relayEvents(this.palette, ["select"]);
    if (this.selectHandler) {
        this.on("select", this.selectHandler, this.scope);
    }
};
Ext.extend(Coolite.Ext.ColorItem, Ext.menu.Adapter);

Coolite.Ext.ColorMenu = function(config) {
    Coolite.Ext.ColorMenu.superclass.constructor.call(this, config);
    this.plain = true;
    var ci = new Coolite.Ext.ColorItem(config);
    this.add(ci);     
    this.palette = ci.palette;
    this.relayEvents(ci, ["select"]);
};
Ext.extend(Coolite.Ext.ColorMenu, Ext.menu.Menu);

Ext.override(Ext.CycleButton, {
    initComponent: function() {
        this.addEvents("change");

        if (this.changeHandler) {
            this.on("change", this.changeHandler, this.scope || this);
            delete this.changeHandler;
        }

        this.itemCount = this.menu.items.length;

        this.menu.cls = "x-cycle-menu";
        var checked;
        for (var i = 0, len = this.itemCount; i < len; i++) {
            var item = this.menu.items.itemAt(i);

            item.group = item.group || this.id;
            
            item.itemIndex = i;
            item.on("checkchange", this.checkHandler, this);
            item.scope = this;
            item.setChecked(item.checked || false, true);

            if (item.checked) {
                checked = item;
            }
        }
        this.setActiveItem(checked, true);
        Ext.CycleButton.superclass.initComponent.call(this);

        this.on("click", this.toggleSelected, this);
    }
});

Ext.override(Ext.menu.Menu, {
    lastTargetIn: function(cmp) {
        var el = cmp.getEl ? cmp.getEl() : cmp;
        return Ext.fly(el).contains(this.trg);
    },

    createEl: function() {
        var frm = document.body;
        if (document.forms.length > 0) {
            frm = document.forms[0];
        }
        return new Ext.Layer({
            cls: "x-menu",
            shadow: this.shadow,
            shim: this.shim || true,
            constrain: false,
            parentEl: this.parentEl || frm,
            zindex: 15000
        });
    }
});

Coolite.Ext.ElementMenuItem = function(cfg) {
    this.target = cfg.target;        
    Coolite.Ext.ElementMenuItem.superclass.constructor.call(this, cfg);
};

Ext.extend(Coolite.Ext.ElementMenuItem, Ext.menu.BaseItem, {
    hideOnClick: false,
    itemCls: "x-menu-item",
    shift: true,

    getComponent: function() {
        if (Ext.isEmpty(this.el.id)) {
            return null;
        }
        var cmp = Ext.getCmp(this.el.id);
        if (Ext.isEmpty(cmp)) {
            return null;
        }
        return cmp;
    },

    // private
    onRender: function(container) {

        if (this.target.getEl) {
            this.el = this.target.getEl();
        }
        else {
            this.el = Ext.$(this.target);
        }

        var cmp = Ext.getCmp(this.el.id);
        this.parentMenu.on("show", function() {
            if (!Ext.isEmpty(cmp)) {
                if (cmp.doLayout) {
                    cmp.doLayout();
                }

                if (cmp.syncSize) {
                    cmp.syncSize();
                }
            }
        });

        if (Ext.isIE) {
            this.parentMenu.shadow = false;
            this.parentMenu.el.shadow = false;

            if (!Ext.isEmpty(cmp)) {
                cmp.shadow = false;
                cmp.el.shadow = false;
            }
        }

        if (this.shift) {
            this.el.applyStyles({ "margin-left": "23px" });
        }

        this.el.swallowEvent(["keydown", "keypress"]);
        Ext.each(["keydown", "keypress"], function(eventName) {
            this.el.on(eventName, function(e) {
                if (e.isNavKeyPress()) {
                    e.stopPropagation();
                }
            }, this);
        }, this);

        if (Ext.isGecko) {
            container.removeClass("x-menu-list-item");
            container.setStyle({ width: "", height: "" });
            if (this.shift) {
                this.el.applyStyles({ "margin-left": "24px" });
            }
        }

        Coolite.Ext.ElementMenuItem.superclass.onRender.apply(this, arguments);
    },

    activate: function() {
        if (this.disabled) {
            return false;
        }

        var cmp = this.getComponent();
        if (Ext.isEmpty(cmp)) {
            return false;
        }

        this.cmp.focus();
        this.fireEvent("activate", this);
        return true;
    },

    // private
    deactivate: function() {
        this.fireEvent("deactivate", this);
    },

    // private
    disable: function() {
        var cmp = this.getComponent();
        if (Ext.isEmpty(cmp)) {
            return;
        }
        this.cmp.disable();
        Coolite.Ext.ElementMenuItem.superclass.disable.call(this);
    },

    // private
    enable: function() {
        var cmp = this.getComponent();
        if (Ext.isEmpty(cmp)) {
            return;
        }
        this.cmp.enable();
        Coolite.Ext.ElementMenuItem.superclass.enable.call(this);
    }
});

Coolite.Ext.ComboMenuItem = function(config) {
    Coolite.Ext.ComboMenuItem.superclass.constructor.call(this, new Ext.form.ComboBox(config.combobox), config);
    this.combo = this.component;
    this.addEvents("select");
    this.combo.on("render", function(combo) {
        combo.getEl().swallowEvent("click");
        combo.list.applyStyles("z-index:99999");
        combo.list.on("mousedown", function(e) {
            Ext.lib.Event.stopPropagation(e);
        });
    });
};

Ext.extend(Coolite.Ext.ComboMenuItem, Ext.menu.Adapter, {
    hideOnClick: false,
    onSelect: function(combo, record) {
        this.fireEvent("select", this, record);
        Coolite.Ext.ComboMenuItem.superclass.handleClick.call(this);
    },
    onRender: function(container) {
        Coolite.Ext.ComboMenuItem.superclass.onRender.call(this, container);

        if (Ext.isIE) {
            this.combo.list.shadow = false;
        }

        this.el.swallowEvent(["keydown", "keypress"]);
        Ext.each(["keydown", "keypress"], function(eventName) {
            this.el.on(eventName, function(e) {
                if (e.isNavKeyPress()) {
                    e.stopPropagation();
                }
            }, this);
        }, this);

        if (Ext.isGecko) {
            container.setOverflow("auto");
            var containerSize = container.getSize();
            this.combo.wrap.setStyle("position", "fixed");
            container.setSize(containerSize);
        }
    }
});

Coolite.Ext.EditMenuItem = function(config) {
    Coolite.Ext.EditMenuItem.superclass.constructor.call(this, new Ext.form.TextField(config.textbox), config);
    this.textbox = this.component;
    this.addEvents("select");
    this.textbox.on("render", function(textbox) {
        textbox.getEl().swallowEvent("click");
    });
};

Ext.extend(Coolite.Ext.EditMenuItem, Ext.menu.Adapter, {
    onRender: function(container) {
        Coolite.Ext.EditMenuItem.superclass.onRender.call(this, container);

        this.el.swallowEvent(["keydown", "keypress"]);
        Ext.each(["keydown", "keypress"], function(eventName) {
            this.el.on(eventName, function(e) {
                if (e.isNavKeyPress()) {
                    e.stopPropagation();
                }
            }, this);
        }, this);

        if (Ext.isGecko) {
            this.el.setOverflow("auto");
            var containerSize = container.getSize();
            this.textbox.getEl().setStyle("position", "fixed");
            container.setSize(containerSize);
        }
    }
});

Coolite.Ext.MenuPanel = function(config) {
    Coolite.Ext.MenuPanel.superclass.constructor.call(this, config);
    this.menu.on("itemclick", this.setSelection, this);
};

Ext.extend(Coolite.Ext.MenuPanel, Ext.Panel, {
    saveSelection: true,
    selectedIndex: -1,

    initComponent: function() {
        Coolite.Ext.MenuPanel.superclass.initComponent.call(this);        

        if (this.selectedIndex > -1) {
            this.menu.items.get(this.selectedIndex).cls = "x-menu-item-active";
        }
    },

    setSelectedIndex: function(index) {
        this.setSelection(this.menu.items.get(index));
    },

    setSelection: function(item, e) {
        if (this.saveSelection) {
            this.menu.items.each(function(item) {
                item.removeClass("x-menu-item-active");
            }, this.menu);

            item.addClass("x-menu-item-active");
        }

        var f = Ext.get(String.format("{0}_SelIndex", this.id));

        if (!Ext.isEmpty(f)) {
            f.dom.value = this.menu.items.indexOf(item);
        }
    },

    afterRender: function() {
        Coolite.Ext.MenuPanel.superclass.afterRender.call(this);
        var layer = this.menu.getEl();
        if (Ext.isIE) {
            layer.shadow = false;
        }

        this.body.appendChild(layer);
        layer.clearPositioning("auto");
        layer.setWidth("auto");
        layer.setHeight("100%");
        layer.applyStyles({ border: "0px" });
        layer.show();
    }
});
Ext.reg("menupanel", Coolite.Ext.MenuPanel);

// monkey-patch Toolbar.Item .getEl() to return a typeof Element
Ext.Toolbar.Item.prototype.getEl = function() {
    return Ext.$(this.el);
};

Ext.Toolbar.TextItem.override({
    setText: function(text) {
        this.el.innerHTML = text;
    }
});

Ext.override(Ext.form.TextField, {
    truncate: true,
    afterRender: function() {
        Ext.form.TextField.superclass.afterRender.call(this);
        if (this.maxLength !== Number.MAX_VALUE && this.truncate) {
            this.el.dom.setAttribute("maxlength", this.maxLength);
        }
    }
});

Coolite.Ext.TreePanel = function(config) {
    Coolite.Ext.TreePanel.superclass.constructor.call(this, config);
};

Ext.extend(Coolite.Ext.TreePanel, Ext.tree.TreePanel, {
    initComponent: function() {
        Coolite.Ext.TreePanel.superclass.initComponent.call(this);
        this.initChildren(this.nodes);
    },

    initChildren: function(nodes) {
        if (!Ext.isEmpty(nodes) && nodes.length > 0) {
            var root = nodes[0];
            var rootNode = this.createNode(root);
            this.setRootNode(rootNode);

            if (root.children) {
                this.setChildren(root, rootNode);
            }
        }
    },

    setChildren: function(parent, node) {
        for (var i = 0; i < parent.children.length; i++) {
            var child = parent.children[i];
            var childNode = this.createNode(child);
            node.appendChild(childNode);
            if (child.children) {
                this.setChildren(child, childNode);
            }
        }
    },

    createNode: function(config) {
        var type = config.nodeType || "node";
        if (type == "node") {
            return new Ext.tree.TreeNode(config);
        }

        return new Ext.tree.AsyncTreeNode(config);
    }
});

Ext.reg("coolitetreepanel", Coolite.Ext.TreePanel);

//    Ext.util.Observable.prototype.fireEvent = Ext.util.Observable.prototype.fireEvent.createInterceptor(function() {
//        if (!(this.isAjaxInit || false)) {
//            this.isAjaxInit = true;

//            if (this.ajaxEvents) {
//                this.on(this.ajaxEvents);
//            }            
//        }
//    });

Ext.override(Ext.util.Observable,{
    init_ev: function() {
        if (!(this.isPostBackInit || false)) {
            this.isPostBackInit = true;

            if (this.postBacks) {
                this.on(this.postBacks);
            }
        }
    
        if (!(this.isAjaxInit || false)) {
            this.isAjaxInit = true;

            if (this.ajaxEvents) {
                this.on(this.ajaxEvents);
            }
        }
    }
});

Coolite.AjaxEvent = new Ext.data.Connection({
    autoAbort: false,
    serializeForm: function(form) {
        return Ext.lib.Ajax.serializeForm(form);
    },
    setValue: function(form, name, value) {
        var input = null;
        if (form[name]) {
            input = form[name];
        } else {
            input = document.createElement("input");
            input.setAttribute("name", name);
            input.setAttribute("type", "hidden");
        }
        input.setAttribute("value", value);
        var parentElement = input.parentElement ? input.parentElement : input.parentNode;
        if (parentElement === null) {
            form.appendChild(input);
            form[name] = input;
        }
    },
    delayedF: function(el, remove) {
        if (!Ext.isEmpty(el)) {
            el.unmask();
            if (remove === true) {
                el.remove();
            }
        }
    },
    showFailure: function(response) {
        var win = new Ext.Window({ modal: true, width: 500, height: 300, title: "Request Failure", layout: "fit", maximizable: true,
            listeners: {
                "maximize": {
                    fn: function(el) {
                        var v = Ext.getBody().getViewSize();
                        el.setSize(v.width, v.height);
                    },
                    scope: this
                }
            },
            items: new Ext.form.FormPanel({
                baseCls: "x-plain",
                layout: "absolute",
                autoScroll: true,
                defaultType: "textfield",
                items: [
                {
                    x: 5,
                    y: 5,
                    xtype: "label",
                    html: '<div class="x-window-dlg"><div class="ext-mb-error" style="width:32;height:32"></div></div>'
                },{
                    x: 42,
                    y: 6,
                    xtype: "label",
                    html: "<b>Status code: </b>"
                },{
                    x: 115,
                    y: 6,
                    xtype: "label",
                    text: response.status
                },{
                    x: 42,
                    y: 25,
                    xtype: "label",
                    html: "<b>Status text: </b>"
                },{
                    x: 115,
                    y: 25,
                    xtype: "label",
                    text: response.statusText
                },{
                    x: 0,
                    y: 42,
                    xtype: "htmleditor",
                    anchor: "100% 100%",
                    enableAlignments: false,
                    enableAlignments: false,
                    enableColors: false,
                    enableFont: false,
                    enableFontSize: false,
                    enableFormat: false,
                    enableLinks: false,
                    enableLists: false,
                    enableSourceEdit: false,
                    value: response.responseText
                }]
                })
            });
            win.show();
        },
        parseResponse: function(response) {
            var text = response.responseText,
            xmlTpl = "<?xml",
            result = {},
            exception = false;

            result.success = true;

            try {
                if (response.responseText.match(/^<\?xml/) == xmlTpl) {
                    //xml parsing      
                    var xmlData = response.responseXML;
                    var root = xmlData.documentElement || xmlData;
                    var q = Ext.DomQuery;

                    if (root.nodeName == "AjaxResponse") {
                        //root = q.select("AjaxResponse", root);
                        //success
                        var sv = q.selectValue("Success", root, true);
                        var pSuccess = sv !== false && sv !== "false";

                        //error
                        var pErrorMessage = q.selectValue("ErrorMessage", root, "");

                        //script
                        var pScript = q.selectValue("Script", root, "");

                        //viewState
                        var pViewState = q.selectValue("ViewState", root, "");

                        //viewStateEncrypted
                        var pViewStateEncrypted = q.selectValue("ViewStateEncrypted", root, "");

                        //eventValidation
                        var pEventValidation = q.selectValue("EventValidation", root, "");

                        //serviceResponse
                        var pServiceResponse = q.selectValue("ServiceResponse", root, "");

                        //ExtraParamsResponse
                        var pUserParamsResponse = q.selectValue("ExtraParamsResponse", root, "");

                        //Result
                        var pResult = q.selectValue("Result", root, "");

                        if (!Ext.isEmpty(pSuccess)) {
                            Ext.apply(result, { success: pSuccess });
                        }

                        if (!Ext.isEmpty(pErrorMessage)) {
                            Ext.apply(result, { errorMessage: pErrorMessage });
                        }

                        if (!Ext.isEmpty(pScript)) {
                            Ext.apply(result, { script: pScript });
                        }

                        if (!Ext.isEmpty(pViewState)) {
                            Ext.apply(result, { viewState: pViewState });
                        }

                        if (!Ext.isEmpty(pViewStateEncrypted)) {
                            Ext.apply(result, { viewStateEncrypted: pViewStateEncrypted });
                        }

                        if (!Ext.isEmpty(pEventValidation)) {
                            Ext.apply(result, { eventValidation: pEventValidation });
                        }

                        if (!Ext.isEmpty(pServiceResponse)) {
                            Ext.apply(result, { serviceResponse: eval("(" + pServiceResponse + ")") });
                        }

                        if (!Ext.isEmpty(pUserParamsResponse)) {
                            Ext.apply(result, { extraParamsResponse: eval("(" + pUserParamsResponse + ")") });
                        }

                        if (!Ext.isEmpty(pResult)) {
                            Ext.apply(result, { result: eval("(" + pResult + ")") });
                        }

                        return { result: result, exception: false }
                    }
                    else {
                        text = root.text || root.textContent;
                    }
                }

                //json parsing
                result = eval("(" + text + ")");

            } catch (e) {
                result.success = false;
                exception = true;
                if (response.responseText.length === 0) {
                    result.errorMessage = "NORESPONSE";
                } else {
                    result.errorMessage = "BADRESPONSE: " + e.message;
                    result.responseText = response.responseText;
                }

                response.statusText = result.errorMessage;
            }

            return { result: result, exception: exception };
        },
        listeners: {
            beforerequest: {
                fn: function(conn, options) {
                    o = options || {};
                    o.eventType = o.eventType || "event";

                    var isStatic = o.eventType == "static",
                        isInstance = o.eventType == "instance",
                        isRequired = o.eventType == "event" || o.eventType == "custom" || o.eventType == "proxy" || o.eventType == "postback";

                    var submitConfig = {};
                    o.extraParams = o.extraParams || {};

                    switch (o.eventType) {
                        case "event":
                        case "custom":
                        case "proxy":
                        case "postback":
                        case "instance":
                            if (isInstance) {
                                o.action = o.methodName;
                            }

                            o.control = o.control || {};
                            o.type = o.type || "submit";
                            o.viewStateMode = o.viewStateMode || "default";
                            o.action = o.action || "Click";
                            if (o.type == "submit") {
                                o.form = Ext.$(o.formProxyArg);
                            }

                            o.headers = { "X-Coolite": "delta=true" };

                            if (o.type == "submit" && Ext.isEmpty(o.form) && !Ext.isEmpty(o.control.el)) {
                                if (Ext.isEmpty(o.control.isComposite) || o.control.isComposite === false) {
                                    o.form = o.control.el.up("form");
                                }
                                else {
                                    o.form = Ext.$(o.control.elements[0]).up("form");
                                }
                            } else if (o.type == "load" && Ext.isEmpty(o.method)) {
                                o.method = "GET";
                            }

                            var argument = String.format("{0}|{1}|{2}", o.proxyId || o.control.proxyId || o.control.id || "-", o.eventType, o.action);

                            if (!Ext.isEmpty(o.form)) {
                                this.setValue(o.form.dom, "__EVENTTARGET", Coolite.Ext.ScriptManagerUniqueID);
                                this.setValue(o.form.dom, "__EVENTARGUMENT", argument);
                                Ext.getDom(o.form).ignoreAllSubmitFields = true;
                            } else {
                                o.url = o.url || Coolite.Ext.Url || window.location.href;
                                if (o.url.substring(o.url.length - 1) === "/") {
                                    o.url = o.url + "?"; //.substring(0, o.url.length - 1);
                                }
                                Ext.apply(submitConfig, { __EVENTTARGET: Coolite.Ext.ScriptManagerUniqueID, __EVENTARGUMENT: argument });
                            }

                            if (o.viewStateMode != "default") {
                                Ext.apply(submitConfig, { viewStateMode: o.viewStateMode });
                            }

                            if (o.before) {
                                if (o.before(o.control, o.eventType, o.action, o.extraParams) === false) {
                                    return false;
                                }
                            }

                            Ext.apply(submitConfig, { extraParams: o.extraParams || {} });

                            if (!Ext.isEmpty(o.serviceParams)) {
                                Ext.apply(submitConfig, { serviceParams: o.serviceParams });
                            }

                            o.params = { submitAjaxEventConfig: Ext.encode({ config: submitConfig }) };

                            break;
                        case "static":
                            o.headers = { "X-Coolite": "staticmethod=true" };

                            //                            if (o.type == "load") {
                            //                                o.method = "GET";
                            //                            }

                            o.url = o.url || Coolite.Ext.Url || window.location.href;
                            if (o.url.substring(o.url.length - 1) === "/") {
                                o.url = o.url + "?";
                            }

                            if (o.before) {
                                if (o.before(o.control, o.eventType, o.action, o.extraParams) === false) {
                                    return false;
                                }
                            }

                            Ext.apply(o.extraParams, { "_methodName_": o.methodName });
                            o.params = o.extraParams;
                            break;
                    }

                    o.scope = this;

                    //--Common part----------------------------------------------------------

                    var el, em = o.eventMask || {};

                    if ((em.showMask || false)) {
                        switch (em.target || "page") {
                            case "this":
                                if (o.control.getEl) {
                                    el = o.control.getEl();
                                } else if (o.control.dom) {
                                    el = o.control;
                                }
                                break;
                            case "parent":
                                if (o.control.getEl) {
                                    el = o.control.getEl().parent();
                                } else if (o.control.parent) {
                                    el = o.control.parent();
                                }
                                break;
                            case "page":
                                el = Ext.getBody().createChild({ style: "position:absolute;left:0;top:0;width:100%;height:100%;z-index:20000;background-color:Transparent;" });
                                var scroll = Ext.getBody().getScroll();
                                el.setLeftTop(scroll.left, scroll.top);
                                break;
                            case "customtarget":
                                var trg = em.customTarget || "";
                                el = Ext.$(trg);
                                if (Ext.isEmpty(el)) {
                                    el = trg.getEl ? trg.getEl() : null;
                                }
                                break;
                        }

                        if (el !== undefined && el !== null) {
                            el.mask(em.msg || "Working...", em.msgCls || "x-mask-loading");
                            o.el = el;
                        }
                    }

                    var removeMask = function(o) {
                        if (o.el !== undefined && o.el !== null) {
                            var delay = 0,
                                em = o.eventMask || {};
                            if (em && em.minDelay) {
                                delay = em.minDelay;
                            }

                            var remove = (em.target || "page") == "page",
                            task = new Ext.util.DelayedTask(
                                function(o, remove) {
                                    o.scope.delayedF(o.el, remove);
                                },
                                o.scope,
                                [o, remove]
                            ).delay(delay);
                        }
                    };

                    var executeScript = function(o, result, response) {
                        var delay = 0;
                        var em = o.eventMask || {};
                        if (em.minDelay) {
                            delay = em.minDelay;
                        }

                        var task = new Ext.util.DelayedTask(
                            function(o, result, response) {
                                if (result.script && result.script.length > 0) {
                                    eval(result.script);
                                }

                                if (o.userSuccess) {
                                    o.userSuccess(response, result, o.control, o.eventType, o.action, o.extraParams, o);
                                }
                            },
                            o.scope, [o, result, response]).delay(delay);
                    };


                    o.failure = function(response, options) {
                        var o = options;
                        removeMask(o);
                        if (o.userFailure) {
                            o.userFailure(response, { "errorMessage": response.statusText }, o.control, o.eventType, o.action, o.extraParams, o);
                        } else {
                            if (o.showWarningOnFailure !== false) {
                                o.scope.showFailure(response);
                            }
                        }
                    };

                    o.success = function(response, options) {
                        var o = options;
                        removeMask(o);

                        var parsedResponse = o.scope.parseResponse(response);
                        var result = parsedResponse.result;
                        var exception = parsedResponse.exception;

                        if (result.success === false) {

                            if (o.userFailure) {
                                o.userFailure(response, result, o.control, o.eventType, o.action, o.extraParams, o);
                            } else {
                                if (o.showWarningOnFailure !== false) {
                                    if (!exception) {
                                        response.responseText = result.errorMessage + " | Response: " + response.responseText;
                                    }
                                    o.scope.showFailure(response);
                                }
                            }

                            return;
                        }

                        if (!Ext.isEmpty(result.viewState) && o.form !== null) {
                            o.scope.setValue(o.form.dom, "__VIEWSTATE", result.viewState);

                            if (!Ext.isEmpty(result.viewStateEncrypted) && o.form !== null) {
                                o.scope.setValue(o.form.dom, "__VIEWSTATEENCRYPTED", result.viewStateEncrypted);
                            }

                            if (!Ext.isEmpty(result.eventValidation) && o.form !== null) {
                                o.scope.setValue(o.form.dom, "__EVENTVALIDATION", result.eventValidation);
                            }
                        }

                        executeScript(o, result, response);
                    };
                }
            }
        }
    });

    Coolite.AjaxMethod = {
        request: function(methodName, config) {
            config = config || {};
            Coolite.AjaxEvent.request({
                methodName: methodName,
                control: Ext.isEmpty(config.control) ? undefined : {id: config.control},
                eventType: config.methodType || "instance",
                type: config.type || "load",
                method: config.httpMethod || "POST",
                extraParams: config.params,
                url: config.url,
                ajaxMethodSuccess: config.success,
                ajaxMethodFailure: config.failure,
                userSuccess: function(response, result, control, eventType, action, extraParams, o) {
                    if (!Ext.isEmpty(o.ajaxMethodSuccess)) {
                        o.ajaxMethodSuccess(result.result);
                    }
                },
                userFailure: function(response, result, control, eventType, action, extraParams, o) {
                    if (!Ext.isEmpty(o.ajaxMethodFailure)) {
                        o.ajaxMethodFailure(result.errorMessage);
                    }
                }
            });
        }
    };
        

Ext.Panel.override({
    getCollapsedField: function() { return Ext.get(String.format("{0}_Collapsed", this.id)); },        

    getBody: function() {
        return Ext.get(this.id + "_Body") || this.body;
    },

    setAutoScroll: function() {
        if (this.rendered && this.autoScroll) {
            var el = this.body || this.el;
            if (el) {
                el.setOverflow("auto");
                // Following line required to fix autoScroll
                el.dom.style.position = "relative";
            }
        }
    },

    showIFrameMask: false,

    loadIFrame: function(url) {
        if (Ext.isEmpty(this.iframe)) {
            var iframeObj = {
                tag: "iframe",
                width: "100%",
                height: "100%",
                frameborder: 0,
                id: this.id + "_IFrame",
                name: this.id + "_IFrame",
                src: url
            };
            this.iframe = Ext.get(Ext.DomHelper.insertFirst(this.body, iframeObj));
            this.iframe.on("load", this.afterLoad, this);
            this.fireEvent("beforeiframeload", this, this.iframe);
        }
        else {
            this.fireEvent("beforeiframeload", this, this.iframe, this.iframe.dom.src);
            this.iframe.dom.src = url;
        }

        if (this.showIFrameMask) {
            this.body.mask(this.iFrameMaskMsg || "Loading..."); 
        }
    },

    afterLoad: function() {
        if (this.showIFrameMask) {
            this.body.unmask();
        }
        this.fireEvent("afteriframeload", this, this.iframe, this.iframe.dom.src);
    },

    doIFrameAutoLoad: function() {
        this.loadIFrame(this.autoLoadIFrame);
    },

    refreshIFrame: function() {
        if (!Ext.isEmpty(this.iframe)) {
            this.loadIFrame(this.iframe.dom.src);
        }
    }
});

Ext.Panel.prototype.initComponent = Ext.Panel.prototype.initComponent.createSequence(function() {        
    this.addEvents("beforeiframeload", "afteriframeload");
    if (this.autoLoadIFrame) {
        this.on("render", this.doIFrameAutoLoad, this, { delay: 10 });
    }
});

Ext.Panel.prototype.onCollapse = Ext.Panel.prototype.onCollapse.createSequence(function(doAnim, animArg) {
    var f = this.getCollapsedField();
    if (!Ext.isEmpty(f)) {
        f.dom.value = "true";
    }
});

Ext.Panel.prototype.onExpand = Ext.Panel.prototype.onExpand.createSequence(function(doAnim, animArg) {
    var f = this.getCollapsedField();
    if (!Ext.isEmpty(f)) {
        f.dom.value = "false";
    }
});

Coolite.Ext.TaskResponse = { stopTask: -1, stopAjax: -2};

Coolite.Ext.TaskManager = function(config) {
    Coolite.Ext.TaskManager.superclass.constructor.call(this);
    Ext.apply(this, config);
    return new Ext.util.DelayedTask(this.initManager, this).delay(this.autoRunDelay || 50);
};

Ext.extend(Coolite.Ext.TaskManager, Ext.util.Observable, {
    tasksConfig: [],
    tasks: [],

    getTasks: function() { return this.tasks; },

    initManager: function() {
        this.runner = new Ext.util.TaskRunner(this.interval || 10);
        var task;
        for (var i = 0; i < this.tasksConfig.length; i++) {
            task = this.createTask(this.tasksConfig[i]);
            this.tasks.push(task);
            if (task.executing && task.autoRun) {
                this.startTask(task);
            }
        }
    },

    getTask: function(id) {
        if (typeof id == "object") {
            return id;
        } else if (typeof id == "string") {
            for (var i = 0; this.tasks.length; i++) {
                if (this.tasks[i].id == id) {
                    return this.tasks[i];
                }
            }
        } else if (typeof id == "number") {
            return this.tasks[id];
        }
        return null;
    },

    startTask: function(task) {
        if (this.executing) {
            return;
        }

        task = this.getTask(task);

        if (task.onstart) {
            task.onstart.apply(task.scope || task);
        }

        this.runner.start(task);
    },

    stopTask: function(task) { this.runner.stop(this.getTask(task)); },

    startAll: function() {
        for (var i = 0; i < this.tasks.length; i++) {
            this.startTask(this.tasks[i]);
        }
    },

    stopAll: function() { this.runner.stopAll(); },

    //private
    createTask: function(config) {
        return Ext.apply({}, config, {
            owner: this,
            executing: true,
            interval: 1000,
            autoRun: true,
            onStop: function(t) {
                this.executing = false;
                if (this.onstop) {
                    this.onstop();
                }
            },
            run: function() {
                if (this.clientRun) {
                    var rt = this.clientRun.apply(arguments);

                    if (rt === Coolite.Ext.TaskResponse.stopAjax) {
                        return;
                    } else if (rt === Coolite.Ext.TaskResponse.stopTask) {
                        return false;
                    }
                }
                if (this.serverRun) {
                    var params = arguments;
                    this.serverRun.control = this.owner;
                    Coolite.AjaxEvent.request(this.serverRun);
                }
            }
        });
    }
});

Coolite.Ext.WebServiceTreeLoader = Ext.extend(Ext.tree.TreeLoader, {
    // private override
    processResponse : function(response, node, callback){
        var xmlData = response.responseXML;
        var root = xmlData.documentElement || xmlData;
        var json = Ext.DomQuery.selectValue("json", root, "");
        
        try {
            var o = eval("("+json+")");
            node.beginUpdate();
            for(var i = 0, len = o.length; i < len; i++){
                var n = this.createNode(o[i]);
                if(n){
                    node.appendChild(n);
                }
            }
            node.endUpdate();
            if(typeof callback == "function"){
                callback(this, node);
            }
        }catch(e){
            this.handleFailure(response);
        }
    }
});

Coolite.Ext.lazyInit = function (controls) {
    if (!Ext.isArray(controls)) { return; }
    for (var i = 0; i < controls.length; i++) {
        window[controls[i]] = Ext.getCmp(controls[i]);
    }
};

Coolite.Ext.setValues = function(controls) {
    if (!Ext.isArray(controls)) { return; }
    for (var i = 0; i < controls.length; i++) {
        controls[i][0].setValue(controls[i][1]);
        controls[i][0].clearInvalid();
    }
};

Coolite.Ext.doPostBack = function(config) {
    if (config.before) {
        if (config.before(config.control, config.extraParams || {}) === false) {
            return;
        }
    }

    if (config.extraParams) {        
        var form = document.forms[0];
        if (!Ext.isEmpty(form)) {
            form = Ext.get(form);
            var id = "__CoolitePostBackParams";            
            var el = form.insertFirst({ tag: "input", id: id, name: id, type: "hidden" });
            el.dom.value = Ext.encode(config.extraParams);
        }
    }

    config.fn();
};

Coolite.Ext.TriggerField = Ext.extend(Ext.form.TriggerField, {
    initComponent: function() {
        Coolite.Ext.TriggerField.superclass.initComponent.call(this);

        this.addEvents("triggerclick");

        if (this.triggersConfig) {

            var cn = [];
            for (var i = 0; i < this.triggersConfig.length; i++) {
                var trigger = this.triggersConfig[i];
                var triggerCfg = {
                    tag: "img",
                    "ext:qtip":trigger.qtip || "",
                    src: Ext.BLANK_IMAGE_URL,
                    cls: "x-form-trigger" + (trigger.triggerCls || "") + " " + (trigger.iconCls || "x-form-ellipsis-trigger")
                };

                if (trigger.hideTrigger) {
                    Ext.apply(triggerCfg, { style: "display:none" });
                }
                cn.push(triggerCfg);
            }

            this.triggerConfig = { tag: 'span', cls: 'x-form-twin-triggers', cn: cn };
        }
    },

    getTrigger: function(index) {
        return this.triggers[index];
    },

    initTrigger: function() {
        var ts = this.trigger.select('.x-form-trigger', true);
        this.wrap.setStyle('overflow', 'hidden');
        var triggerField = this;
        ts.each(function(t, all, index) {
            t.hide = function() {
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = 'none';
                triggerField.el.setWidth(w - triggerField.trigger.getWidth());
            };
            t.show = function() {
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = '';
                triggerField.el.setWidth(w - triggerField.trigger.getWidth());
            };

            t.on("click", this.onTriggerClick, this, { index: index, t: t, preventDefault: true });
            t.addClassOnOver('x-form-trigger-over');
            t.addClassOnClick('x-form-trigger-click');
        }, this);
        this.triggers = ts.elements;
    },

    onTriggerClick: function(evt, el, o) {
        this.fireEvent("triggerclick", this, o.t, o.index);
    }
});
Ext.reg('cooltrigger', Coolite.Ext.TriggerField);

Ext.form.DateField.override({
    onTriggerClick: function() {
        if (this.disabled) {
            return;
        }
        if (this.menu == null) {
            this.menu = new Ext.menu.DateMenu();
        }
        Ext.apply(this.menu.picker, {
            minDate: this.minValue,
            maxDate: this.maxValue,
            disabledDatesRE: this.ddMatch,
            disabledDatesText: this.disabledDatesText,
            disabledDays: this.disabledDays,
            disabledDaysText: this.disabledDaysText,
            format: this.format,
            showToday: this.showToday,
            minText: String.format(this.minText, this.formatDate(this.minValue)),
            maxText: String.format(this.maxText, this.formatDate(this.maxValue))
        });
        
        if(this.cancelText){
            Ext.apply(this.menu.picker, {cancelText : this.cancelText});
        }        
        if(this.dayNames){
            Ext.apply(this.menu.picker, {dayNames : this.dayNames});
        }
        if(this.monthNames){
            Ext.apply(this.menu.picker, {monthNames : this.monthNames});
        }
        if(this.monthYearText){
            Ext.apply(this.menu.picker, {monthYearText : this.monthYearText});
        }
        if(this.nextText){
            Ext.apply(this.menu.picker, {nextText : this.nextText});
        }
        if(this.okText){
            Ext.apply(this.menu.picker, {okText : this.okText});
        }
        if(this.prevText){
            Ext.apply(this.menu.picker, {prevText : this.prevText});
        }
        if(this.startDay){
            Ext.apply(this.menu.picker, {startDay : this.startDay});
        }
        if(this.todayText){
            Ext.apply(this.menu.picker, {todayText : this.todayText});
        }
        if(this.todayTip){
            Ext.apply(this.menu.picker, {todayTip : this.todayTip});
        }
        
        this.menu.on(Ext.apply({}, this.menuListeners, {
            scope: this
        }));
        this.menu.picker.setValue(this.getValue() || new Date());
        this.menu.show(this.el, "tl-bl?");
    }
});

Ext.apply(Ext.form.VTypes, {
    daterange: function(val, field) {
        var date = field.parseDate(val);

        var dispUpd = function(picker) {
            var ad = picker.activeDate;
            picker.activeDate = null;
            picker.update(ad);
        };

        if (field.startDateField) {
            var sd = Ext.getCmp(field.startDateField);
            sd.maxValue = date;
            if (sd.menu && sd.menu.picker) {
                sd.menu.picker.maxDate = date;
                dispUpd(sd.menu.picker);
            }
        }
        else if (field.endDateField) {
            var ed = Ext.getCmp(field.endDateField);
            ed.minValue = date;
            if (ed.menu && ed.menu.picker) {
                ed.menu.picker.minDate = date;
                dispUpd(ed.menu.picker);
            }
        }
        return true;
    }
});

if (Ext.isIE) {
    Ext.util.CSS.createStyleSheet(".x-btn button { width: 100%; }");
}

if(typeof Sys!=="undefined"){Sys.Application.notifyScriptLoaded();}if(typeof Sys!=="undefined"){Sys.Application.notifyScriptLoaded();}